package com.example.xd.phone_album

import android.content.ContentUris
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import java.io.File

/**
 * @auther XuDan on 2020/8/13.
 */
abstract class ScanFragment : Fragment() {
    companion object {
        val MEDIA_TYPE_VIDEO = 1
        val MEDIA_TYPE_PIC = 2
        val MEDIA_TYPE_ALL = 3
    }

    var scanFileList: MutableList<SingleImageModel> = mutableListOf()

    var handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                1 -> {
                    scanDialogDismiss()
                }
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(getLayoutId(), container, false)
    }

    abstract fun getLayoutId(): Int

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        scan()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView(view)
    }

    abstract fun initView(view: View)

    fun scan() {
        when (getScanType()) {
            MEDIA_TYPE_VIDEO -> {
                scanVideo()
            }
            MEDIA_TYPE_PIC -> {
                scanPic()
            }
            MEDIA_TYPE_ALL -> {
                scanAll()
            }
        }
    }

    /**
     * 扫描所有内容
     */
    private fun scanAll() {
    }

    /**
     * 扫描图片
     */
    private fun scanPic() {
        val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val contentResolver = activity!!.getContentResolver()
        var cursor = contentResolver.query(
            uri,
            null,
            MediaStore.Images.Media.MIME_TYPE + "=\"image/jpeg\" or " +
                    MediaStore.Images.Media.MIME_TYPE + "=\"image/png\"",
            null,
            MediaStore.Images.Media.DATE_MODIFIED + " desc"
        )
        if (cursor != null) {
            scanDialogShow()
            scanFileList.clear()
            while (cursor.moveToNext()) {
                var singleImageModel = SingleImageModel()
                singleImageModel.type = SingleImageModel.TYPE_PIC
                singleImageModel.date =
                    cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media.DATE_MODIFIED))
                singleImageModel.id =
                    cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID))
                singleImageModel.isSelect = false
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                    singleImageModel.path =
                        cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
                } else {
                    val id = cursor.getLong(cursor.getColumnIndex(MediaStore.MediaColumns._ID))
                    val uri =
                        ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
                    singleImageModel.path = uri.toString()
                }
                var file = File(singleImageModel.path)
                if (file.exists()) {
                    scanFileList.add(singleImageModel)
                }
            }
            cursor.close()
            var s = SingleImageModel()
            s.isSelect = false
            s.type = SingleImageModel.TYPE_PIC
            scanFileList.add(0, s)
            handler.sendEmptyMessageDelayed(1, 1000)
        }
    }

    /**
     * 扫描视频
     */
    private fun scanVideo() {
        val mediaColumns = arrayOf<String>(
            MediaStore.Video.Media.DATA,
            MediaStore.Video.Media._ID,
            MediaStore.Video.Media.TITLE,
            MediaStore.Video.Media.MIME_TYPE,
            MediaStore.Video.Media.DATE_MODIFIED
        )
        val contentResolver = activity?.getContentResolver()
        val coursor = contentResolver?.query(
            MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
            mediaColumns,
            null,
            null,
            null
        )
        if (coursor != null) {
            scanDialogShow()
            scanFileList.clear()
            while (coursor.moveToNext()) {
                var singleImageModel = SingleImageModel()
                singleImageModel.type = SingleImageModel.TYPE_VIDEO
                singleImageModel.id =
                    coursor.getInt(coursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID))
                        .toLong()
                singleImageModel.path =
                    coursor.getString(coursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA))
                singleImageModel.date =
                    coursor.getLong(coursor.getColumnIndex(MediaStore.Video.Media.DATE_MODIFIED))
                singleImageModel.mime_type =
                    coursor.getString(coursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE))
                singleImageModel.isSelect = false
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                    singleImageModel.path =
                        coursor.getString(coursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA))
                } else {
                    val id = coursor.getLong(coursor.getColumnIndex(MediaStore.MediaColumns._ID))
                    val uri =
                        ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id)
                    singleImageModel.path = uri.toString()
                }
                var file = File(singleImageModel.path)
                if (file.exists() && file.length() > 0) {
                    scanFileList.add(singleImageModel)
                }

            }
            var s = SingleImageModel()
            s.isSelect = false
            s.type = SingleImageModel.TYPE_VIDEO
            scanFileList.add(0, s)
            coursor.close()
            handler.sendEmptyMessageDelayed(1, 1000)

        }
    }

    abstract fun getScanType(): Int
    fun scanDialogDismiss() {}
    fun scanDialogShow() {}

}